package com.pn.taikao.controller;

import com.pn.taikao.dto.ApiResponse;
import com.pn.taikao.dto.CourseQueryRequest;
import com.pn.taikao.dto.CreateResponse;
import com.pn.taikao.dto.PageResult;
import com.pn.taikao.entity.Course;
import com.pn.taikao.entity.User;
import com.pn.taikao.service.CourseService;
import com.pn.taikao.utils.SecurityUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/courses")
public class CourseController {

    private final CourseService courseService;

    public CourseController(CourseService courseService) {
        this.courseService = courseService;
    }

    /**
     * 创建课程（教师权限）
     */
    @PostMapping
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<CreateResponse> create(@RequestBody Course course) {
        // 从当前登录用户获取教师ID
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }
        
        // 设置创建者
        course.setCreateBy(SecurityUtils.getCurrentUsername());
        
        // 如果teacherId为空，设置为当前用户ID
        if (course.getTeacherId() == null) {
            course.setTeacherId(currentUserId);
        }
        
        Long id = courseService.createCourse(course);
        return ApiResponse.success(new CreateResponse(id));
    }

    /**
     * 更新课程（教师权限，只能更新自己创建的课程）
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<Void> update(@PathVariable("id") Long id, @RequestBody Course course) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }
        
        // 检查是否是课程创建者或管理员
        Course existCourse = courseService.getById(id);
        if (existCourse == null) {
            return ApiResponse.error("课程不存在");
        }
        
        // 管理员可以修改任何课程，教师只能修改自己创建的课程
        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser != null && !currentUser.getRoleType().equalsIgnoreCase("ADMIN")) {
            if (!existCourse.getTeacherId().equals(currentUserId)) {
                return ApiResponse.error("无权限修改该课程");
            }
        }
        
        course.setId(id);
        course.setUpdateBy(SecurityUtils.getCurrentUsername());
        courseService.updateCourse(course);
        return ApiResponse.success(null);
    }

    /**
     * 删除课程（教师权限，只能删除自己创建的课程）
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<Void> delete(@PathVariable("id") Long id) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }
        
        // 检查是否是课程创建者或管理员
        Course existCourse = courseService.getById(id);
        if (existCourse == null) {
            return ApiResponse.error("课程不存在");
        }
        
        // 管理员可以删除任何课程，教师只能删除自己创建的课程
        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser != null && !currentUser.getRoleType().equalsIgnoreCase("ADMIN")) {
            if (!existCourse.getTeacherId().equals(currentUserId)) {
                return ApiResponse.error("无权限删除该课程");
            }
        }
        
        courseService.deleteCourse(id);
        return ApiResponse.success(null);
    }

    /**
     * 查询课程详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER','STUDENT')")
    public ApiResponse<Course> detail(@PathVariable("id") Long id) {
        Course course = courseService.getById(id);
        if (course == null) {
            return ApiResponse.error("课程不存在");
        }
        return ApiResponse.success(course);
    }

    /**
     * 获取当前教师的所有课程
     */
    @GetMapping("/my")
    @PreAuthorize("hasRole('TEACHER')")
    public ApiResponse<List<Course>> getMyCourses() {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }
        List<Course> courses = courseService.getByTeacherId(currentUserId);
        return ApiResponse.success(courses);
    }

    /**
     * 根据学院ID获取课程列表（不分页，用于下拉选择）
     */
    @GetMapping("/college/{collegeId}")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER','STUDENT')")
    public ApiResponse<List<Course>> getByCollege(@PathVariable("collegeId") Long collegeId) {
        List<Course> courses = courseService.getByCollegeId(collegeId);
        return ApiResponse.success(courses);
    }

    /**
     * 分页查询课程列表
     */
    @PostMapping("/query")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER','STUDENT')")
    public ApiResponse<PageResult<Course>> list(@RequestBody CourseQueryRequest request) {
        // 处理默认值
        int page = (request.getPage() != null && request.getPage() > 0) ? request.getPage() : 1;
        int size = (request.getSize() != null && request.getSize() > 0) ? request.getSize() : 10;
        
        // 如果不是管理员，教师只能查看自己的课程
        Long teacherId = request.getTeacherId();
        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser != null && !currentUser.getRoleType().equalsIgnoreCase("ADMIN")) {
            if (currentUser.getRoleType().equalsIgnoreCase("TEACHER")) {
                // 教师只能查看自己的课程
                teacherId = SecurityUtils.getCurrentUserId();
            }
        }
        
        List<Course> data = courseService.list(request.getName(), teacherId, request.getCollegeId(), page, size);
        long total = courseService.count(request.getName(), teacherId, request.getCollegeId());
        PageResult<Course> pageResult = new PageResult<>(data, total, page, size);
        return ApiResponse.success(pageResult);
    }
}

